package org.squabble.web.admin;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Validator;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.squabble.domain.Account;
import org.squabble.domain.Privilege;
import org.squabble.service.AccountService;
import org.squabble.service.SearchService;

@Controller
public class AccountCenterController {

	@Autowired
	SearchService searchService;

	@Autowired
	AccountService accountService;
	
	@Autowired
	@Qualifier("validator")
	Validator validator;

	@RequestMapping(value = "/admin/user", method = RequestMethod.GET)
	public String searchSetupForm(ModelMap model) {
		AccountSearchCommand asc = new AccountSearchCommand();
		model.addAttribute("accountSearchCommand", asc);
		List<Privilege> privileges = accountService.getPrivileges();
		privileges.add(0, new Privilege());
		model.addAttribute("privileges", privileges);
		List<Account> accounts = searchService.getNewAccounts();
		model.addAttribute("newAccounts", accounts);
		return "admin.account.center";
	}

	@RequestMapping(value = "/admin/user/search", method = RequestMethod.POST)
	public String searchAccounts(
			@ModelAttribute("accountSearchCommand") AccountSearchCommand asc,
			BindingResult results, ModelMap model) {
		validator.validate(asc, results);
		if (results.hasErrors()) {
			return "ajax:admin.account.search.results";
		}
		List<Account> accounts = searchService.searchAccounts(asc.getName(),
				asc.getEmail(), asc.getPrivilegeId());
		model.addAttribute("accounts", accounts);
		return "ajax:admin.account.search.results";
	}
}
